package ru.hh.team02.chat.test;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;

import ru.hh.team02.chat.utils.StringSocket;

/*
 * dummy client for testing purposes
 */
public class AnotherClient {
    private StringSocket requestSocket;

    private static Random random = new Random();
    
    public static String nameClient;

    public static void main(final String args[]) {
        for (int i = 0; i < 10; ++i) {
            new Thread() {
                @Override
                public void run() {
                    AnotherClient client = new AnotherClient();
                    client.run();
                }
            }.start(); 
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private void run() {
        try {
            requestSocket = new StringSocket(new Socket("localhost", 2004));
            System.out.println("connected to localhost in port 2004");

            requestSocket.write("r1");
            requestSocket.write("name" + random.nextInt());
            
            new Thread() {
                @Override
                public void run() {
                    for (int j = 0; j < 10000; ++j) {
                        try {
                            requestSocket.write("tralala");
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                }
            }.start(); 

            String message = "";
            do {                
                if (requestSocket.available()) {
                    handleMessage(requestSocket.read());
                }
            } while (!message.equals("exit"));
        } catch (UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        } catch (IOException ioException) {
            //ioException.printStackTrace();
            System.out.println("lalala");
        } finally {
            if (requestSocket != null) requestSocket.close();
        }
    }

    private void handleMessage(String message) {
        System.out.println(message);
    }

}

